<script setup lang='ts'>
//引入xuanzhuan的代码
import router from '@/router';
import { useComponents } from '../stores/counter'
import RotateIndex from '@/components/rOtate/index.vue'
const { canvasComponents, currentcom }: any = storeToRefs(useComponents())
import Critical_love from '@/views/center.vue'
import { storeToRefs } from 'pinia';
//2.启用Dom元素
import { onMounted, ref, onUnmounted, watch } from 'vue';
// 添加一个变量来跟踪当前选择的形状  
const SvgShape = ref('line'); // 初始化为画线  
const selectedShape = ref(''); // 初始状态为空字符串或默认的形状
function drawlove(event: MouseEvent) {
  if (!isDrawing || !ctx) return;
  // 如果需要清除，可以在这里调用 clearCanvas() 函数  

  switch (SvgShape.value) {
    case 'line':
      // 原来的线绘制代码  
      break;
    case 'rect':
      // 矩形绘制代码  
      break;
    case 'circle':
      // 圆形绘制代码  
      break;
    // ... 其他形状 ...  
    case 'clear':
      // 橡皮擦逻辑（可能是清除上一个点）  
      break;
    case 'cleararea':
      clearCanvas(); // 清除整个画布  
      break;
  }

}
// 引用canvas元素  
const canvas = ref<HTMLCanvasElement | null>(null);
let ctx: CanvasRenderingContext2D | null = null;

// 绘制状态  
let isDrawing = false;
let startX = 0;
let startY = 0;

// 线条样式  
const lineWidth = ref(2);
const lineColor = ref('red');

// 初始化canvas和上下文  
onMounted(() => {
  if (canvas.value) {
    ctx = canvas.value.getContext('2d');
    if (ctx) {
      ctx.lineCap = 'round';
      canvas.value.width = 500;
      canvas.value.height = 500;
    }
  }
});

// 清理canvas 
function clearCanvas() {
  if (ctx) {
    ctx.clearRect(250, 250, canvas.value?.width ?? 10, canvas.value?.height ?? 10);
  }
}

// 开始绘制  
function startDrawing(event: MouseEvent) {
  isDrawing = true;
  [startX, startY] = [event.offsetX, event.offsetY];
}

// 绘制 直线 
function draw(event: MouseEvent) {
  if (!isDrawing || !ctx) return;
  // clearCanvas(); // 如果需要每次绘制前清除，则取消注释此行  

  const rect = canvas.value?.getBoundingClientRect();
  if (rect) {
    const currentX = event.clientX - rect.left;
    const currentY = event.clientY - rect.top;

    ctx.lineWidth = lineWidth.value;
    ctx.strokeStyle = lineColor.value;
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(currentX, currentY);
    ctx.stroke();
    startX = currentX;
    startY = currentY;

    // 根据选择的形状进行绘图  
    switch (SvgShape.value) {
      case 'line':
        ctx.value.beginPath();
        ctx.value.moveTo(startX.value, startY.value);
        ctx.value.lineTo(currentX, currentY);
        ctx.value.stroke();
        break;
      case 'rect':
        // 这里你需要保存开始绘制的点，并在mouseup时绘制矩形  
        // 暂时省略  
        break;
      case 'circle':
        // 假设在mousedown时保存了圆心，然后在mousemove时根据移动距离确定半径  
        // 暂时省略  
        break;
      case 'clear':
        // 橡皮擦逻辑，可能需要一个更大的画笔来“擦除”  
        // 你可以通过调整lineWidth和strokeStyle来实现  
        ctx.value.globalCompositeOperation = 'destination-out';
        ctx.value.beginPath();
        ctx.value.arc(currentX, currentY, lineWidth.value * 10, 0, Math.PI * 2);
        ctx.value.fill();
        ctx.value.globalCompositeOperation = 'source-over';
        break;
      case 'cleararea':
        clearCanvas();
        break;
      default:
        break;
    }

    // 更新开始绘制的坐标，以便绘制连续的线或形状  
    if (['line', 'rect', 'circle'].includes(SvgShape.value)) {
      startX.value = currentX;
      startY.value = currentY;
    }
  }

}
// }


// 停止绘制  
function stopDrawing() {
  isDrawing = false;
  // 可以在这里添加绘制结束后的处理  
}


let resetDrawing = () => {
  console.log('形状已更改：', selectedShape.value);
}
// 组件卸载时清理  
onUnmounted(() => {
  ctx = null;
});
// 监听 select 的变化  
watch(SvgShape, (newValue, oldValue) => {
  // 当形状改变时，可以重置绘制状态或执行其他逻辑  
  console.log(newValue, oldValue, "====实时监听");

})



//跳转页面   加密评论
const comment = () => {
  router.push('/comment')
}
</script>
<template>
  <div class="paa">
    <div class="left_left">
      <dl style="margin-left: 10px;">
        <dt>选形状：</dt>
        <dd>
          <!-- //1.第一绑定双向v-model   @change事件 -->
          <select v-model="selectedShape" @change="resetDrawing" id="pickShape" tag="shape">
            <option value="line">画线</option>
            <option value="rect">画矩形</option>
            <option value="circle">画圆</option>
            <option value="clear">橡皮擦</option>
            <option value="cleararea">清除区域</option>
          </select>
        </dd>
      </dl>
    </div>
    <div class="zhong">
      <RotateIndex v-for="(item, index) in canvasComponents" :key="index" :id="item.id" :style="item.style">
        <component :is="item.comName" :style="item.style" @mousedown="onmousedown(item.id)"
          v-if="item.comName === 'MyImage'" :imgsrc="item.imgsrc" class="tateIndex" >
        </component>
        <component v-else :is="item.comName" :style="item.style" @mousedown="onmousedown(item.id)">
        </component>
      </RotateIndex>
    </div>
    <canvas class="left_right" ref="canvas" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing"
      @mouseleave="stopDrawing" style="border: 1px solid black;">
      <!-- //3.开始canvas事件  完成这些事件 ref="canvas" @mousemove="Onmousemove" @mouseup="onmouseup" @mousedown="onmousedown" -->
    </canvas>
     <el-icon @click="comment" class="ICON">
        <CameraFilled />
      </el-icon>
  </div>
</template>

<style scoped lang='scss'>
.ICON{
  position: absolute;
  left: 40%;
  font-size: 36px;
  cursor: pointer;
}

.paa {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: palevioletred;
}

.left_left {
  width: 14%;
  height: 1035.6px;
  color: #fff;
  float: left;

}

.zhong {
  width: 55.9%;

  height: 862.9px;
  position: relative; //fu
  background-image: linear-gradient(to right, #ccc 2px, transparent 2px),
    linear-gradient(to bottom, #ccc 2px, transparent 2px);
  background-size: 20px 20px;
  /* 设定格子大小 */
  background-position: 0 0, 0 0;
  /* 确保背景从左上角开始 */
  background-repeat: repeat;
  float: left;


}

.left_right {
  position: absolute;
  width: 30%;
  height: 860.9px;
  background-image: linear-gradient(to right, #ccc 2px, transparent 2px),
    linear-gradient(to bottom, #ccc 2px, transparent 2px);
  background-size: 20px 20px;
  /* 设定格子大小 */
  background-position: 0 0, 0 0;
  /* 确保背景从左上角开始 */
  background-repeat: repeat;
  
}
</style>